package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 该线程负责与指定的客户端完成http交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            String line = readline();
            System.out.println(line);
            String method = line.split("\\s")[0];
            String uri = line.split(" ")[1];
            String protocol = line.split(" ")[2];
            System.out.println(method+"---"+uri+"---"+protocol);
            Map<String,String> headers = new HashMap<>();
            while (true){
                line = readline();
                if(line.isEmpty()){
                    break;
                }
               // System.out.println(line);
                headers.put(line.split(":\\s")[0],line.split(":\\s")[1]);
            }
            Set<Map.Entry<String,String>> set = headers.entrySet();
            /*for (Map.Entry<String,String> entry:set
                 ) {
                System.out.println(entry.getKey()+"-"+entry.getValue());
            }*/
            System.out.println(headers);
            //System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String readline() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder str = new StringBuilder();
        char pre = 'a', now = 'a';
        int d;
        while ((d = in.read()) != -1) {
            now = (char) d;
            if (pre == 13 & now == 10) {
                break;
            }
            str.append(now);
            pre = now;
        }
        return str.toString().trim();
    }
}
